@echo off
setlocal enabledelayedexpansion
chcp 65001 > nul
title ev

:: Environment variables
set workspace=%userprofile%\workspace
set softSpace=C:
set rootSpace=C:
set tempPath=C:\tmp
set notice=">>>"
set JAVA_HOME=%softSpace%\App\SDK_JAVA\jdk-8u431-windows-x64\jdk1.8.0_431
set M2X_HOME=%softSpace%\App\BTS\apache-maven
set GIT_HOME=%softSpace%\App\BTS\PortableGit
set MSQ_HOME=%softSpace%\App\BTS\mysql\bin
set NGX_HOME=%softSpace%\App\WWW_nginx
set path=%path%;%JAVA_HOME%\bin
set path=%path%;%M2X_HOME%\bin
set path=%path%;%GIT_HOME%\bin;C:\Program Files\Git\bin
set demoRoot=%workspace%\demo
set target=%workspace%\preDeploy
set deploy=%workspace%\preDeploy
set "terminal=%demoRoot%\matrix_shell\scripts"

:: Start background task
REM Check if background task is already running
tasklist | findstr /i "background_task.bat" >nul 2>nul
if %errorlevel% equ 0 (
    echo Background task is already running.
) else (
    REM Start background task from plugins directory without showing window
    if exist "%terminal%\plugins\background_task.bat" (
        start /min /b cmd /c "%terminal%\plugins\background_task.bat"
        echo Background task started.
    ) else (
        echo Warning: Background task script not found.
    )
)
echo.

:loop
cd /d %terminal% 2>nul
title ev
set "vOrder="
set /p vOrder=[%username%@local]$

REM Check if empty or only spaces
if not "%vOrder%"=="" set vOrder=%vOrder:"=%
if "%vOrder%"=="" (
    goto :loop
) else if "%vOrder%"=="a" (
    call :show_quotes
    goto :loop
) else if "%vOrder%"=="doc" (
    cd "%userprofile%/workspace/" 2>nul
    explorer .
    goto :loop
) else if "%vOrder%"=="q" (
    call :cleanup
    echo Press any key to exit...
    pause >nul
    goto :eof
) else if "%vOrder%"=="guu" (
    echo "%vOrder%"
    call :guu
    goto :loop
) else if "%vOrder%"=="h" (
    call :help
    goto :loop
) else if "%vOrder%"=="windows" (
    call :windows
    goto :loop
) else (
    REM Check if the command corresponds to an internal function
    REM First, try to call the internal function directly
    call :%vOrder% 2>nul
    if errorlevel 1 (
        REM If internal function doesn't exist, try to call go.sh script using bash
        if exist "%terminal%\go.sh" (
            bash "%terminal%\go.sh" %vOrder%
        ) else (
            echo Command not found: %vOrder%
            echo Press any key to continue...
            pause >nul
        )
    )
    goto :loop
)

:: Cleanup function to terminate background processes
:cleanup
echo Terminating background processes...
REM Simplified and reliable approach to terminate background processes

REM First, terminate the specific background_task.bat process
wmic process where "commandline like '%background_task.bat%'" call terminate >nul 2>&1

REM Wait a moment for processes to terminate gracefully
ping 127.0.0.1 -n 2 >nul

REM Terminate timeout.exe safely
wmic process where "name='timeout.exe'" call terminate >nul 2>&1

REM Use taskkill with window title filter to avoid killing the main window
REM This is safer than using process ID filtering
wmic process where "name='cmd.exe' AND commandline like '%background_task%' AND NOT commandline like '%launcher.cmd%'" call terminate >nul 2>&1

echo Background processes terminated.
goto :eof

:guu
echo [info] Update action not available in standalone mode.
goto :eof

:: Kill processes by image name prefix
:doAnythingKill
set app=%1
if "%app%"=="" goto :eof
echo "[vOrder] - 0 - %app%"
tasklist | findstr /i "%app%*"
TASKKILL /F /IM "%app%*" /T > nul
goto :eof

:: HotLauncher - Python program launcher with lock mechanism
:hotlauncher
REM Check if the program is really running
set "LOCK_FILE=%USERPROFILE%\workspace\ev\hotlauncher.lock"

if exist "%LOCK_FILE%" (
    REM Read PID from lock file
    set "PID="
    for /f "delims=" %%i in ('type "%LOCK_FILE%" 2^>nul') do set "PID=%%i"

    if defined PID (
        REM Check if process with this PID is still running
        tasklist /fi "PID eq %PID%" /fo csv 2>nul | findstr /i "python.exe" >nul
        if errorlevel 1 (
            REM Process is not running, delete the lock file
            echo Cleaning up leftover lock file...
            del /f "%LOCK_FILE%" 2>nul >nul
        ) else (
            REM Process is still running, show message to user
            echo Program is already running (PID: %PID%)
            echo The main program is already running in the background.
            echo Look for the icon in the system tray (bottom right corner).
            echo Press any key to continue...
            pause >nul
            goto :eof
        )
    ) else (
        REM Invalid lock file, delete it
        echo Cleaning up invalid lock file...
        del /f "%LOCK_FILE%" 2>nul >nul
    )
)

REM Launch hidden Python process using VBScript
echo Starting program...
if exist "%~dp0run_hidden.vbs" (
    wscript.exe "%~dp0run_hidden.vbs"
) else (
    echo Warning: run_hidden.vbs not found.
    echo Press any key to continue...
    pause >nul
)
goto :eof

:: Remote Desktop quick launcher
:mstsc
if "%1"=="x" (
    start mstsc /v: yamhk /console
) else if "%1"=="2" (
    start mstsc /v: 192.168.179.222         /console
) else if "%1"=="5" (
    start mstsc /v: 192.168.179.25          /console
) else if "%1"=="22" (
    start mstsc /v: yamhk.2288.org:23389    /console
) else if "%1"=="55" (
    start mstsc /v: yamhk.2288.org:53389    /console
) else (
    start mstsc /v: yamhk.2288.org          /console
)
goto :eof

:: Open some common URLs
:y
start chrome.exe "http://www.yamhk.top/"
goto :eof
:b
start chrome.exe https://www.baidu.com
goto :eof
:g
start chrome.exe https://www.google.com
goto :eof
:f
start chrome.exe "%userprofile%\workspace\demo\matrix_html\index.html"
goto :eof

:: Agents/Servers (requires jars under %deploy%)
:a
if exist "%deploy%/www_static/s_agent/agent.jar" (
    cd /d %terminal%/shell 2>nul
    java -Xms256m -Xmx512m -Dfile.encoding=utf-8 -jar %deploy%/www_static/s_agent/agent.jar
) else (
    echo Agent jar not found at %deploy%/www_static/s_agent/agent.jar
    echo Press any key to continue...
    pause >nul
)
goto :eof
:s
if exist "%deploy%/www_static/s_meta/matrix-core-server-release.jar" (
    cd /d %terminal%/shell 2>nul
    java -Xms256m -Xmx512m -Dfile.encoding=utf-8 -jar %deploy%/www_static/s_meta/matrix-core-server-release.jar
) else (
    echo Meta server jar not found at %deploy%/www_static/s_meta/matrix-core-server-release.jar
    echo Press any key to continue...
    pause >nul
)
goto :eof

:: Update config and package
:cuw
@echo off&title doUpdateConfig
echo "dir rebuild"
rd /s /q "%workspace%/preDeploy/" 2>nul
cd "/" 2>nul
md "%workspace%/preDeploy/" 2>nul
md "%workspace%/preDeploy/temp" 2>nul
cd %deploy% 2>nul
md "html" 2>nul
md "www_static/s_meta/" 2>nul
md "www_static/b_html/" 2>nul
md "www_static/b_html/cert/" 2>nul

:: Copy Matrix Java jar file
if exist "%workspace%\demo\matrix_java\target\matrix_java-1.0.0.RELEASE.jar" (
    echo Copying Matrix Java jar file to %deploy%/www_static/s_meta/
    mkdir "%deploy%/www_static/s_meta" >nul 2>nul
    copy "%workspace%\demo\matrix_java\target\matrix_java-1.0.0.RELEASE.jar" "%deploy%/www_static/s_meta/" >nul 2>nul
    if errorlevel 1 (
        echo Error: Failed to copy Matrix Java jar file
    ) else (
        echo Matrix Java jar file copied successfully
    )
) else (
    echo Warning: Matrix Java jar file not found at %workspace%\demo\matrix_java\target\matrix_java-1.0.0.RELEASE.jar
)


:: Copy static files to deployment directory
cd %terminal%/plugins/ 2>nul
echo copy  -html: copying static files
:: Use more reliable robocopy command instead of xcopy
if exist "%workspace%/demo/matrix_html" (
    echo Copying files from %workspace%/demo/matrix_html to %deploy%/html
    robocopy "%workspace%/demo/matrix_html" "%deploy%/html" /E /NFL /NDL /NJH /NJS /nc /ns /np >nul 2>nul
    if errorlevel 8 (
        echo Error: Robocopy failed with serious error
    ) else (
        echo Files copied successfully with robocopy
    )
) else (
    echo Warning: Source directory does not exist: %workspace%/demo/matrix_html
)

echo "copy-shell"
cd %demoRoot%/matrix_shell/scripts/tools 2>nul
copy *.sh "%deploy%/www_static/" >nul 2>nul
copy *.sh "%deploy%/html/" >nul 2>nul
cd %demoRoot%/matrix_shell/scripts/plugins 2>nul
copy *.sh "%deploy%/www_static/" >nul 2>nul
copy *.sh "%deploy%/html/" >nul 2>nul

echo "package-html-to-war"
cd %deploy% 2>nul
cd html 2>nul
:: First, try to create WAR package using jar command
jar -cvf ../html.war * >nul 2>nul
if errorlevel 1 (
    echo "Warning: jar command failed, trying alternative methods..."
    :: Alternative 1: Use Python to create ZIP file (WAR is actually ZIP format)
    python -c "import zipfile, os; f=zipfile.ZipFile('../html.war','w',zipfile.ZIP_DEFLATED); [f.write(os.path.join(r,n),os.path.join(r,n)) for r,d,_ in os.walk('.') for n in _]; f.close()" >nul 2>nul
    if errorlevel 1 (
        echo "Warning: Python zip method failed"
        :: Alternative 2: Check if 7-Zip is available
        where 7z >nul 2>nul
        if errorlevel 1 (
            echo "Warning: 7-Zip not found"
        ) else (
            7z a -tzip ../../html.war * >nul 2>nul
        )
    ) else (
        echo "html.war created using Python zip method"
    )
) else (
    echo "html.war created using jar command"
)
@REM cd .. & rd /s /q "html"
@ping 127.0.0.1 -n 3 >nul

:: Packaging related operations
:: Ensure b_html directory exists and create html.war file first, then perform copy operations
echo "Creating b_html directory and copying files"
cd "%deploy%/www_static" 2>nul
:: Ensure b_html directory exists
if not exist "b_html" md "b_html"
if not exist "b_html/cert" md "b_html/cert"

:: Copy script files to b_html directory first
copy do*.sh "%deploy%/www_static/b_html" >nul 2>nul
copy go_java_mac.sh "%deploy%/www_static/s_meta/go.sh" >nul 2>nul

:: Delete script files in www_static directory
del *.sh >nul 2>nul

:: Move war file to b_html directory (ensure html.war file has been created)
cd /d %terminal%/plugins 2>nul
echo "move war to html package"
cd %deploy% 2>nul
:: Ensure html.war file exists before copying
if exist "html.war" (
    copy html.war "www_static/b_html/" >nul 2>nul
    echo "html.war copied to b_html directory"
) else (
    echo "Warning: html.war not found, creating it now..."
    cd html 2>nul
    if exist "*" (
        :: First, try to create WAR package using jar command
        jar -cvf ../www_static/b_html/html.war * >nul 2>nul
        if errorlevel 1 (
            echo "Warning: jar command failed, trying alternative methods..."
            :: 备选方案1：使用Python创建ZIP文件（WAR实际上是ZIP格式）
            python -c "import zipfile, os; f=zipfile.ZipFile('../www_static/b_html/html.war','w',zipfile.ZIP_DEFLATED); [f.write(os.path.join(r,n),os.path.join(r,n)) for r,d,_ in os.walk('.') for n in _]; f.close()" >nul 2>nul
            if errorlevel 1 (
                echo "Warning: Python zip method failed"
                :: 备选方案2：检查是否有7-Zip可用
                where 7z >nul 2>nul
                if errorlevel 1 (
                    echo "Warning: 7-Zip not found"
                ) else (
                    7z a -tzip ../../www_static/b_html/html.war * >nul 2>nul
                )
            ) else (
                echo "html.war created using Python zip method"
            )
        ) else (
            echo "html.war created using jar command"
        )
        echo "html.war created and copied to b_html directory"
    ) else (
        echo "Error: No files found in html directory to create war package"
    )
    cd ..
)

:: 检查b_html目录中是否包含html.war文件
cd "%deploy%/www_static" 2>nul
if not exist "b_html/html.war" (
    echo "Error: html.war not found in b_html directory"
    echo "Attempting to create html.war directly in b_html directory..."
    cd "%deploy%/html" 2>nul
    if exist "*" (
        :: First, try to create WAR package using jar command
        jar -cvf ../www_static/b_html/html.war * >nul 2>nul
        if errorlevel 1 (
            echo "Warning: jar command failed, trying alternative methods..."
            :: Alternative 1: Use Python to create ZIP file (WAR is actually ZIP format)
            python -c "import zipfile, os; f=zipfile.ZipFile('../www_static/b_html/html.war','w',zipfile.ZIP_DEFLATED); [f.write(os.path.join(r,n),os.path.join(r,n)) for r,d,_ in os.walk('.') for n in _]; f.close()" >nul 2>nul
            if errorlevel 1 (
                echo "Warning: Python zip method failed"
                :: Alternative 2: Check if 7-Zip is available
                where 7z >nul 2>nul
                if errorlevel 1 (
                    echo "Warning: 7-Zip not found"
                ) else (
                    7z a -tzip ../../www_static/b_html/html.war * >nul 2>nul
                )
            ) else (
                echo "html.war created using Python zip method"
            )
        ) else (
            echo "html.war created using jar command"
        )
        echo "html.war created directly in b_html directory"
    ) else (
        echo "Error: No files found in html directory to create war package"
    )
)

:: Delete war files in deploy directory
del *.war >nul 2>nul

echo "package html package"
cd "%deploy%/www_static" 2>nul
:: Finally check to ensure b_html directory contains html.war file
if exist "b_html/html.war" (
    tar -cvf tmp.tar b_html >nul 2>nul
    echo "tmp.tar created successfully with html.war included"
) else (
    echo "Error: html.war not found in b_html directory. Package creation failed."
)
echo "package html package"
cd "%deploy%/www_static" 2>nul
rd /s /q "b_html" >nul 2>nul

echo "Configuration update and packaging operations completed"
goto :eof
:qv
cd /d "%softSpace%/App/BTS/gg_v2ray/Qv2ray-v2.7.0-Windows/deployment/" 2>nul
if exist "qv2ray.exe" (
    start qv2ray.exe
) else (
    echo Qv2ray not found.
    echo Press any key to continue...
    pause >nul
)
cd /d %terminal% 2>nul
goto :eof
:cmd
start cmd.exe
goto :eof
:ssh
cd %softSpace%/App/BTS/SecureCRT/
if exist "SecureCRTPortable.exe" (
    start SecureCRTPortable.exe
) else (
    echo SecureCRT not found.
)
goto :eof
:open
set url=https://www.baidu.com
set url=https://bc.yamhk.top/hk/v1/hk?content='open '%1
echo %url%
curl %url% 2>nul
echo Press any key to continue...
pause >nul
goto :eof
:.
explorer .
goto :eof
:pot
cd /d "%softSpace%/App/BTS/PotPlayer" 2>nul
if exist "PotPlayerMini.exe" (
    start PotPlayerMini.exe
) else (
    echo PotPlayer not found.
    echo Press any key to continue...
    pause >nul
)
cd /d %terminal% 2>nul
goto :eof
:cls
cls
goto :eof
:pwd
echo %cd%
echo Press any key to continue...
pause >nul
goto :eof
:ls
dir
echo Press any key to continue...
pause >nul
goto :eof
:shut
shutdown /s -t 1
goto :eof
:reboot
shutdown /r -t 1
goto :eof
:: Show quotes function
:show_quotes
echo.
echo "Quotes will be displayed here"
echo.
echo Press any key to continue...
pause >nul
goto :eof

:: Windows function (download Git)
:windows
echo Downloading latest Git for Windows to downloads folder...
:: Add actual download logic here if needed
echo Download initiated.
echo Press any key to continue...
pause >nul
goto :eof

:: Show help information
:help
echo.
echo ========================================
echo           www.cmd command help
echo ========================================
echo.
echo System control commands:
echo   doc     - Open workspace directory
echo   q       - Exit program
echo   guu     - Update project (not available in standalone mode)
echo   help/h  - Show this help information
echo   windows - Download latest Git for Windows to downloads folder
echo.
echo Network and proxy commands:
echo   u       - Enable proxy
echo   d       - Disable proxy
echo   db      - Backup nginx config
echo.
echo Remote desktop commands:
echo   mstsc   - Remote desktop connection (supports params: x, 1-5, m, 11-55)
echo.
echo Web access commands:
echo   b       - Open Baidu
echo   g       - Open Google
echo   open    - Open specified content via API
echo.
echo Nginx operation commands:
echo   ngs     - Start nginx
echo   ngr     - Restart nginx
echo   ngd     - Stop nginx
echo.
echo Java tool commands:
echo   jvm     - Start Java VisualVM
echo.
echo Server commands:
echo   a       - Start agent server
echo   s       - Start meta server
echo.
echo Application launch commands:
echo   hotlauncher - Start Python program (with lock mechanism)
echo   init    - Initialize system integration
echo   qv      - Start Qv2ray
echo   cmd     - Open command prompt
echo   gba     - Start Git Bash
echo   pot     - Start PotPlayer
echo   ij      - Start IntelliJ IDEA
echo   dg      - Start DataGrip
echo   ws      - Start WebStorm
echo   py      - Start PyCharm
echo   hx      - Start HBuilderX
echo.
echo System tool commands:
echo   .       - Open current directory
echo   rek     - Restart explorer
echo   rel     - Start explorer
echo   cls     - Clear screen
echo   rg      - Open registry editor
echo   pwd     - Show current path
echo   ls      - Show directory contents
echo   shut    - Shutdown
echo   reboot  - Reboot
echo.
echo ========================================
echo Note: If you enter a non-existent command, the go.sh script will be called automatically
echo ========================================
echo.
echo Press any key to continue...
pause >nul
goto :eof